import {$post,$get} from '../util/request.js'
export default {
	namespaced: true,

	state() {

		return {
			checkidx:0,
			addressList:[],
			city:null
			// addressList: [{
			// 	username: '卢本伟',
			// 	phone: '123456789',
			// 	city: '上海',
			// 	region: '区域',
			// 	detail: '详细区域',
			// 	isdefault: true
			// },{
			// 	username: 'pdd',
			// 	phone: '987654321',
			// 	city: '北京',
			// 	region: '区域',
			// 	detail: '详细区域',
			// 	isdefault: false
			// }]
		}
	},
	getters:{
		orderAddress(state){
			let{checkidx,addressList} = state

			if(checkidx !=-1){
				return addressList[checkidx]
			}
			for(let i=0;i<addressList.length;i++){
				if(addressList[i].isdefault){
					return addressList[i]
				}
			}
		}
	},
	mutations:{
		AddressDefaultMut(state,index){//设为默认
			state.addressList.forEach((item,i)=>{
				if(i == index){
					item.isdefault = true
				}else{
					item.isdefault = false
				}
			})
		},
			
		AddressSwitch(state,index){
			state.checkidx = index
			uni.navigateBack({
				
			})
		},
		AddressaddMut(state,addressobj){
			console.log(state.addressList);
			state.addressList.push(addressobj)
		},
			
		Addressinit(state,addressobj){
			
			state.addressList = addressobj.results
			console.log(state.addressList);
		},
		
		AddCity(state,name){
			state.city = name
		}
		
	},
	actions:{
			
		Addressaddact(context,addressObj){
			$post('/1.1/classes/address',addressObj).then(({objectId})=>{
				// 这里的context好像就相当于this.$store  
				//     Action 提交的是 mutation，而不是直接变更状态。
    // Action 可以包含任意异步操作。
	
	// 异步请求用actions 同步用mutations
				context.commit('AddressaddMut',{
					...addressObj,
					objectId
				})
				uni.navigateBack({
					
				})
			})
		},
			
		Addressinitact(context,userid){
			let url = `/1.1/classes/address?where={"userid":"${userid}"}`
			$get(url).then(res=>{
				console.log(res);
				context.commit('Addressinit',res)
			})
		}
	}
}
